#include <QtCore/QCoreApplication>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QTimer>
#include <QtCore/QDebug>
#include <MNotification>

#define DEBUG() qDebug() << __PRETTY_FUNCTION__ << __LINE__

class Notification : public QObject
{
    Q_OBJECT
public:
    explicit Notification(QObject *parent = 0);

public slots:
    void publish();
    void remove();

private:
    MNotification notification;
};

Notification::Notification(QObject *parent)
    : QObject(parent)
    , notification("DesktopIconsUpdatedEvent")
{
}

void Notification::publish()
{
    QDir dir(qgetenv("XDG_DATA_HOME"));
    dir.mkpath(dir.absoluteFilePath("applications/"));
    if (!dir.exists()) {
        QMetaObject::invokeMethod(qApp, "quit", Qt::QueuedConnection);
        return;
    }

    if (!dir.cd("applications/")) {
        QMetaObject::invokeMethod(qApp, "quit", Qt::QueuedConnection);
        return;
    }

    int count = 2;

    for (int n = 0; n < count; n++) {
        int i = -1;
        for (int j = 0; j < 100; j++) {
            if (!dir.exists(dir.absoluteFilePath(QString("blackblock-%1.desktop").arg(j)))) {
                i = j;
                break;
            }
        }

        if (i < 0) {
            QMetaObject::invokeMethod(qApp, "quit", Qt::QueuedConnection);
            return;
        }


        QString desktopFile = QString("blackblock-%1.desktop").arg(i);
        QFile file(dir.absoluteFilePath(desktopFile));
        if (file.open(QFile::WriteOnly | QFile::Text)) {
            QTextStream out(&file);
            out << "[Desktop Entry]\n"
                << "Encoding=UTF-8\n"
                << "Type=Link\n"
                << "Name=\n"
                << "Icon=" << qApp->applicationDirPath() << "\n"
                << "URL=\n";
            file.close();
        } else {
            DEBUG() << file.errorString();
            QMetaObject::invokeMethod(qApp, "quit", Qt::QueuedConnection);
            return;
        }
    }
    notification.setSummary(tr("Spaces created"));
    notification.setBody(tr("Start editing menu to move them."));
    notification.setImage("/usr/share/icons/hicolor/80x80/apps/blackblock80.png");
    notification.setCount(count);

    if (notification.publish()) {
        QTimer::singleShot(10000, this, SLOT(remove()));
    }
}

void Notification::remove()
{
    notification.remove();
    QMetaObject::invokeMethod(qApp, "quit", Qt::QueuedConnection);
}

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    Notification notification;
    notification.publish();

    return app.exec();
}

#include "main.moc"
